package java_thinking.unit_17._17_9_10;

import java_thinking.unit_14.pets.Pet;

import java.util.Set;
import java.util.TreeSet;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019-04-20 20:05
 */

public class Individual implements Comparable<Individual> {
    private static long counter = 0;
    private final long id = counter++;
    private String name;

    public Individual(String name) {
        this.name = name;
    }

    public Individual() {
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + (name == null ? "" : " " + name);
    }

    public long id() {
        return id;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Individual && id == ((Individual)obj).id;
    }

    @Override
    public int hashCode() {
        int result = 17;
        if (name != null) {
            result = 37 * result + name.hashCode();
            return result;
        }
        result = 37 * result + (int)id;
        return result;
    }

    /**
     * compareTo将产生一个排序序列，排序的规则首先按照实际类型排序，然后如果有名字的话，
     * 按照那么排序，最后按照创建的顺序排序。
     * @param o
     * @return
     */
    @Override
    public int compareTo(Individual o) {
        String first = getClass().getSimpleName();
        String argFirst = o.getClass().getSimpleName();
        int firstCompare = first.compareTo(argFirst);
        if (firstCompare != 0){
            return firstCompare;
        }
        if (name != null && o.name != null) {
            int secondCompare = name.compareTo(o.name);
            if (secondCompare != 0) {
                return secondCompare;
            }
        }
        return Long.compare(o.id, id);
    }

    public static void main(String[] args) {
        Set<Individual> pets = new TreeSet<>();
        Pet pet = new Pet("dog");
        Pet pet1 = new Pet("dog");
        Pet pet2 = new Pet("cat");
        Pet pet3 = new Pet("cat1");

        pets.add(pet);
        pets.add(pet1);
        pets.add(pet2);
        pets.add(pet3);
        System.out.println(pets);
    }
}
